package 程序员面试金典;

import java.util.Arrays;
import java.util.LinkedList;

public class 水域大小 {

    public int[] pondSizes(int[][] land) {
        LinkedList<Integer> list = new LinkedList<>();
        int count=0;
        for (int i = 0; i < land.length; i++) {
            for (int j = 0; j < land[0].length; j++) {
                if (land[i][j]==0){
                    count=dfs(land,i,j);
                    list.add(count);
                }
            }
        }
        int[] array = list.stream().mapToInt(Integer::intValue).toArray();
        Arrays.sort(array);
        return array;
    }

    private int dfs(int[][] land, int i, int j) {
        //最后一个条件，防止重复寻找
        if (i<0 || i>=land.length || j<0 || j>=land[0].length || land[i][j]!=0)
            return 0;
        int count=1;
        land[i][j]=-1;
        count+=dfs(land,i-1,j);
        count+=dfs(land,i+1,j);
        count+=dfs(land,i,j-1);
        count+=dfs(land,i,j+1);
        count+=dfs(land,i-1,j-1);
        count+=dfs(land,i-1,j+1);
        count+=dfs(land,i+1,j-1);
        count+=dfs(land,i+1,j+1);
        return count;
    }
}
